//
//  ConfigMenuForm.swift
//  ZYA
//
//  Created by 邱仙凯 on 2022/7/11.
//  Copyright © 2022 qxk. All rights reserved.
//

import UIKit


let sectionHeaderHeight:CGFloat = 60
// MARK: 主表
class ConfigMenuForm: GlobalFormVC,operatable,refreshable {
    
    // 特殊菜单 id, 如傲农的[个人资料]
    var specialID: String?
    
    var saveingProtect = "" // 保存按钮保护，防止多次点击  为空时表示无网络正在进行   有内容时：文字表示正在进行的网络
    var saveingProjectInfo = "" // 记录一些保存信息, 用于发送邮件时可以获得信息(包含:菜单名称)
    var rootTemp = MainTempModel(JSON:["":""])!
    var listScanResult = ""
    //     var detailsMode = [String]() // 多细表情况下的，单独细表模式
    let detMCount = 5 // 细表1:detail1:1:null:null;
    var main = [String:Any]()
    var oriMain = [String:Any]() // 上一次的字典，主要为了观察值的变化情况
    var beginMain = [String:Any]() // 初始化的主表字典，给保存并新增使用
    var mainHandler = [TempEitem]()// 带有 模板  控件   和附件
    var topTipText: String?
    // 默认一条，但是多细表的时候多一个维度
    lazy var detHandler: [[DetailsTempCom]] = {
        var aArr = [DetailsTempCom]()
        var bArr = [DetailsTempCom]()
        var cArr = [DetailsTempCom]()
        var dArr = [DetailsTempCom]()
        
        var a = [aArr,bArr,cArr,dArr]
        
        return a
    }()
    // 初始化的细表集合，给保存并新增使用 原始模板
    var beginDetHandler : [DetailsTempCom] = {
        
        let a = Array(repeating: DetailsTempCom(), count: 4)
        
        return a
    }()
    var draftDic = [String:Any]()
    var draftBtn:UIBarButtonItem!
    
    var readedDraft = false // 读取了草稿，保存成功后需要清除草稿
    var readingDraft = false // 读取中，防止快速点击，控件还没处理好导致问题
    
    // 预备细表模板，接口返回的模板，只有唯一一个,会受到影响，存储的是被影响过的模板，点击加一条，使用的
    // 就是预备细表模板
    var tempDet : [[TemplateModel]] = {
        var aArr = [TemplateModel]()
        var bArr = [TemplateModel]()
        var cArr = [TemplateModel]()
        var dArr = [TemplateModel]()
        
        var a = [aArr,bArr,cArr,dArr]
        
        return a
    }()
    // 当前细表索引
    var cDIndex = 0
    
    var tempEffectD : [[TemplateModel]] = {
        var aArr = [TemplateModel]()
        var bArr = [TemplateModel]()
        var cArr = [TemplateModel]()
        var dArr = [TemplateModel]()
        
        var a = [aArr,bArr,cArr,dArr]
        
        return a
    }()
    // 持有默认值的细表
    var defaultOneDetail : [[String:Any]] = {
        
        let a = Array(repeating: [String:Any](), count: 4)
        
        return a
    }()
    
    // 自定义按钮传过来的url参数字典
    var fromDifUrlParaDic = [String:String]()
    // 自定义按钮传过来的直接给main字典
    var fromDifStraightDic = [String:Any]()
    
    
    var tempAuditParamC : AuditParamCombine?
    
    // 上一次细表的字典数组，主要为了观察值的变化情况
    var oriDetArr : [[[String:Any]]] = {
        
        let a = Array(repeating: [[String:Any]](), count: 4)
        
        return a
    }()
    
    
    
    
    var ldOriArr = [LianDHandler]()
    var ldShowArr = [LianDHandler]()
    var selected1 = 0
    var selected2 = 0
    var selected3 = 0
    
    var backto:UIViewController.Type?
    var tempEffectM = [TemplateModel]() // 主表影响
    
    
    
    // 分区的头部
     var segZoneV:KSZoneItem?
    
    // 多细表的头部
     var detailSeperate:KSSeperateItem = {
        let appe = KSFormHAppear()
            .contentHight(12)
            .itembgColor(.clear)
        let v = KSSeperateItem(appearance: appe)
        return v
    }()
    var detailZoneV:KSZoneItem = {
        let appe = KSFormHAppear()
        let v = KSZoneItem(appearance:appe)
        return v
    }()
    
    
    var templateHandle = [TemplateModel]()
    var templateDic = [[String:Any]]()
    
    init(rootTemp:MainTempModel,templateHandle:[TemplateModel], templateDic:[[String:Any]]) {
        self.rootTemp = rootTemp
        self.templateHandle = templateHandle
        self.templateDic = templateDic
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = rootTemp.menu_nm
        
        
        configRight()
        registerSome()
        configSaveAc()
        
        var tempMain = [TemplateModel]() // 主表模板
        tempMain = templateHandle.filter { $0.placeFlag == "1"}
        
        
        
        // 为了渔美康识别  下拉选
        
        var dddIndexArr:[(Int,String)] = []
        var anoIndexDic:[String:(Int,String)] = [:]
        for i in 0..<tempMain.count {
            
            if anoIndexDic[tempMain[i].field_annotation.unwrap].isSome {
                dddIndexArr.append(anoIndexDic[tempMain[i].field_annotation.unwrap]!)
                dddIndexArr.append((i,tempMain[i].field_annotation.unwrap))
                
            } else {
                anoIndexDic.updateValue((i,tempMain[i].field_annotation.unwrap), forKey: tempMain[i].field_annotation.unwrap)
            }
        }
        for iii in dddIndexArr {
            if tempMain[iii.0].field_type.unwrap == TemplateType.input.rawValue {
                tempMain[iii.0].ymkD_idNameFlag = "id"
            } else {
                tempMain[iii.0].ymkD_idNameFlag = "name"
            }
        }
        // 为了渔美康识别  下拉选 ---
        
        
        
        let dmTitle = self.rootTemp.multiDetailsTitles
        if dmTitle.count > 0 {
            
            for i in 0..<dmTitle.count {
                tempDet[i] = templateHandle.filter { $0.placeFlag == "2" && $0.detail_nm == dmTitle[i] }
            }
        } else {
            tempDet[0] = templateHandle.filter { $0.placeFlag == "2" }
            
        }
        
        
        
        
        
        tempEffectM = tempMain.filter { $0.effectArr.count > 0 }
        for i in 0..<tempDet.count {
            tempEffectD[i] = tempDet[i].filter { $0.effectArr.count > 0 }
            
        }
        
        // 所有主表模板 先装上
        mainHandler = tempMain.compactMap { TempEitem(temp: $0) }
        
        let pathArrs = url2PathOriParam(self.rootTemp.query_form_url.unwrap)
        let path_dic = url2PathDic(mainDic: self.main,arr: pathArrs.comPa)
        let newDic = deepMerge(path_dic, fromDifUrlParaDic) as! [String:String]
        
        
        if rootTemp.title_item?.count ?? 0 > 0 {
            KSNetwork.shared.doRequest(API.temp(.getTitleItemContent(menu_id: rootTemp.id_key.unwrap))) { (data: BaseResult<OperateResult>) in
                if data.flag == TRUE {
                    self.topTipText = data.infoStr ?? ""
                }
                
                loadMenuData()
            }
        } else {
            loadMenuData()
        }
        
        
        func loadMenuData() {
            if self.excuteType == .add {
                
                KSNetwork.shared.doRequest(API.temp(.path(path: pathArrs.path, paramDic: newDic))) { (data:BaseResult<OperateResult>) in
                    
                    var ddC = [String:Any]()
                    if data.flag == TRUE {
                        if let netMainDic = data.infoDic {
                            ddC = netMainDic
                        }
                    }
                    
                    self.addJoinBaseData(dicCome: ddC)
                }
                
            } else { // .fix .view  .audit
                
                KSNetwork.shared.doRequest(API.temp(.path(path: pathArrs.path, paramDic: newDic))) { (data:BaseResult<OperateResult>) in
                    if data.flag == TRUE {
                        
                        
                        if let iD = data.infoDic {
                            self.main = iD
                        }
                        
                        let dmParams = self.rootTemp.multiDetailsParams
                        if dmParams.count > 0 {
                            
                            for i in 0..<dmParams.count {
                                self.newDealDet(detParam: dmParams[i],dIndex: i)
                            }
                            
                            
                        } else {
                            self.newDealDet(detParam: TKey.details,dIndex: 0)
                            
                        }
                        
                        
                        self.fetchMainFile {
                            self.fetchDetailFile {
                                
                                for i in 0..<self.tempDet.count {
                                    let oriDet = DetailsTempCom(temp: self.tempDet[i], dic: temp2Dic(self.tempDet[i], rootTemp: self.rootTemp))
                                    
                                    var ttt = [DetailsTempCom]()
                                    ttt.appendAndCountH(oriDet,auCombine: self.tempAuditParamC, exType: self.excuteType)
                                    self.beginDetHandler[i] = ttt.first!
                                }
                                
                                
                                
                                
                                self.configRow()
                            }
                        }
                        
                        //                    }
                        
                        
                    } else {
                        KSToast(data.errorCombine.unwrap)
                    }
                }
            }
        }
        
        
        
    }
    // 两种组装方式 1 getform接口   2 读取草稿
    func addJoinBaseData(dicCome:[String:Any],fromDraft:Bool = false) {
        
        bg.removeAllItem()
        for i in 0..<self.detHandler.count {
            self.detHandler[i].removeAll()
        }
        //        segBlockV = nil
        segZoneV = nil
        var tempMain = [TemplateModel]() // 主表模板
        tempMain = templateHandle.filter { $0.placeFlag == "1"}
        
        
        
        // 返回的main 加上自定义跳转直接带来的字段
        self.main = deepMerge(dicCome, self.fromDifStraightDic)
        // 主表初始化数据
        let dicFormTemp = temp2Dic(tempMain,rootTemp: self.rootTemp)
        // 此时main 有三个来源：1 getfrom获取  2 自定义按钮传值  3 模板自带的默认值
        self.main = deepMerge(self.main, dicFormTemp)
        
        
        if fromDraft {
            fetchMainFile_draft {
                
                continiueDet()
                
                
            }
        } else {
            continiueDet()
        }
        
        func continiueDet() {
            
            let dmParams = self.rootTemp.multiDetailsParams
            if dmParams.count > 0 {
                
                for i in 0..<dmParams.count {
                    self.newDealDet(detParam: dmParams[i],dIndex: i,fromDraft: fromDraft)
                }
                
            } else {
                self.newDealDet(detParam: TKey.details,dIndex: 0,fromDraft: fromDraft)
                
            }
            
            
            self.dealDefaultDetail()
            self.beginMain = self.main
            
            // 个人档案特殊处理
            if self.rootTemp.id_key.unwrap == specialID.unwrap {
                self.fetchMainFile {
                    self.fetchDetailFile {
                        self.configRow()
                    }
                }
            } else {
                self.configRow()
            }
            
        }
    }
    
    func dealDefaultDetail() {
        // 赋值一条默认的细表
        let dmTitle = self.rootTemp.multiDetailsTitles
        if dmTitle.count > 0 {
            
            for i in 0..<dmTitle.count {
                if  (self.rootTemp.multiDetailsOperates[i] == "1" || self.rootTemp.multiDetailsOperates[i] == "2")
                        && self.detHandler[i].count < 1 {
                    
                    
                    
                    let oriDet = DetailsTempCom(temp: self.tempDet[i], dic: temp2Dic(self.tempDet[i],rootTemp: self.rootTemp))
                    
                    self.detHandler[i].appendAndCountH(oriDet,auCombine:self.tempAuditParamC, exType: self.excuteType)
                    
                    self.beginDetHandler[i] = oriDet
                }
            }
            
            
        } else {
            if  (self.rootTemp.is_operation_detail == "1" || self.rootTemp.is_operation_detail == "2")
                    && self.detHandler[0].count < 1 {
                
                
                let oriDet = DetailsTempCom(temp: self.tempDet[0], dic: temp2Dic(self.tempDet[0],rootTemp: self.rootTemp))
                    self.detHandler[0].appendAndCountH(oriDet,auCombine: self.tempAuditParamC, exType: self.excuteType)
                
                self.beginDetHandler[0] = oriDet
            }
            
        }
    }
    func registerSome() {
        self.tableVw.register(GlobalSectionHeader.self, forHeaderFooterViewReuseIdentifier: GlobalSectionHeader.identifier)
        tableVw.register(GlobalAddTableCell.self, forCellReuseIdentifier: GlobalAddTableCell.identifier)
        self.tableVw.register(ConfigMenuFormCell.self, forCellReuseIdentifier: ConfigMenuFormCell.identifier)
    }
    // 刚进来处理一下细表  detParam 细表参数名称   dIndex 第几个细表
    func newDealDet(detParam:String,dIndex:Int,fromDraft:Bool = false) {
        
        var detArr = [[String:Any]]()
        if let det = self.main[detParam] as? [[String:Any]] {
            detArr = det
        } else {
            // 去除字符串首尾的双引号和可能的空白字符 字典数组
            let trimmedString = any2Str(self.main[detParam]).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines.union(.init(charactersIn: "\"\"")))
            if let jsonData = trimmedString.data(using: .utf8) {
                do {
                    
                    
                    // 使用 JSONSerialization 解析 Data 为字典数组
                    if let jsonArray = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.mutableContainers) as? [[String: Any]] {
                        
                        detArr = jsonArray
                    }
                    
                    
                } catch {
                    print("Error deserializing JSON: \(error.localizedDescription)")
                }
            }
            
            
            
        }
        
        
        
        
        
        
        
        
        // 处理细表  （单细表和多细表）
        
        
        for i in 0..<detArr.count {
            var one = detArr[i]
            one.updateValue(TRUE, forKey: TKey.openx)
            
            self.detHandler[dIndex].appendAndCountH(DetailsTempCom(temp: self.tempDet[dIndex], dic: one), auCombine:  self.tempAuditParamC, exType: self.excuteType)
            
        }
        
        // 取一下每一组的默认细表
        if self.detHandler[dIndex].count > 0 {
            // 个人档案过滤掉,因为个人档案的修改是以 .add 状态设置的
            if self.rootTemp.id_key.unwrap != specialID.unwrap && self.excuteType == .add && !fromDraft {
                // 新增是 默认细表 为 接口返回  加  配置生成
                self.defaultOneDetail[dIndex] = self.detHandler[dIndex][0].dic
            } else {
                //修改是  默认细表是  配置生成
            }
            
        }
        
        // 细表取出来之后把主表里的细表删了，防止出现意外问题
        self.main[detParam] = nil
        
        
        
    }
    
    
    func configRow() {
        
        if self.rootTemp.setFormButtonTitle {
            configSaveTitle()
        }
        
        self.configView()
        self.configAction()
        
        self.configTempDataSource(true)
        
        self.getAutoScan()
        if  self.detHandler[self.cDIndex].count > 0 {
            self.activeDetailRow(indexx: 0,status: "true",scroll: false)
        }
        self.readingDraft = false
    }
    // 扫码带进来的值，需要获取数据
    func getAutoScan() {
        if  self.listScanResult != "" {
            
            let fiArr = templateHandle.filter { $0.field_nm == rootTemp.scanOutsideParam }
            if fiArr.count > 0 {
                self.continueUrl(onexx: fiArr.first!,scanRest: listScanResult)
            }
            
        }
    }
    func creatWidget() {
        // 用模板生成控件
        for i in 0..<self.mainHandler.count {
            let item = self.mainHandler[i]
            
            // 隐藏的控件也生成出来，以防影响字段那边会设置显示
            if item.temp!.field_type == TemplateType.file.rawValue {//附件类型
                var max = intTran(item.temp!.upload_num_max)
                if max < 1 {
                    max = 1
                }
                let picTypeArr = type2PicType(item.temp!.upload_type.unwrap)
                
                var viewFlag:ImgViewType!
                if isEnableJ(item.temp!,auCombine: self.tempAuditParamC, exType: self.excuteType!) {
                    viewFlag = .editable
                } else {
                    viewFlag = .viewOnly
                }
                let appe = KSImageSelectAppear()
                
//                let minC = item.temp!.upload_num_min.unwrap != "" ?  item.temp!.upload_num_min.unwrap : "0"
                appe.sectionTitle = item.temp!.field_annotation.unwrap 
                //+ "(" + minC + "~" +  item.temp!.upload_num_max.unwrap + "份)"
                var imgH = KSGlobal.screenW/5
                if max > 5 {
                    imgH = imgH * 2
                }
                if item.temp!.field_annotation.unwrap != "" {
                    imgH += imgUtilSectionH
                }
                
                let imageU = KSImageSelectUtil(frame: CGRect(x:0,y:0,width:bg.ks_width ,height:imgH),httpHeader: USERINFO.picUrl.unwrap,maxImgCount: max,numberOfRow: 5,picType: picTypeArr,viewType:viewFlag,appear: appe)
                imageU.ksDelegate = self
                imageU.u_superVC = self
                imageU.tagx = item.temp!.field_nm.unwrap
                imageU.newestShow(arr: item.imgArray)
                self.mainHandler[i].item = imageU
            } else {
                let v = temp2Component(item.temp!,auCombine: self.tempAuditParamC,excuteType: excuteType!)
                self.mainHandler[i].item = v
            }
            
        }
    }
    func configView() {
        
        
        creatWidget()
        
        let segArr = rootTemp.zones.unwrap.components(separatedBy: ",").filter{ $0 !=  "" }
        KSLog("看看zone-- \(segArr)")
        if segArr.count > 0 {
            self.showView(segArr.first)
        } else {
            self.showView()
        }
        
        
    }
    // MARK: 主表  有zone则有分区，没zone就是常规一区
    func showView(_ zone:String? = nil) {
        
        
        
        var showA = [TempEitem]()
        
        if zone.isSome { // 有分区，只有主表有分区
            
            if segZoneV.isNone {
                // 首次加载，分区头部未添加，先添加上
                let segArr = rootTemp.zones.unwrap.components(separatedBy: ",")
                let appe = KSFormHAppear()
                segZoneV = KSZoneItem(appearance:appe)
                segZoneV?.zoneSegV.bgType = .roundBg
                let segMD = segArr.compactMap { SegmenttData(id: "",nm: $0) }
                segZoneV!.setCollecDataSource(arr: segMD)
                segZoneV!.collecSelected = { indx,sdata in
                    self.showView(sdata.nm)
                }
                bg.add(segZoneV!)
            }
            
            
            
            bg.removeFrom(segZoneV!) {
                
                showA = self.mainHandler.filter {isShowJ($0.temp!,auCombine: self.tempAuditParamC,exType: self.excuteType)}.filter { $0.temp!.zone == zone }
                
                
                
                reAddComp()
            }
            
        } else { // 没有分区
            
            
            showA = self.mainHandler.filter {isShowJ($0.temp!,auCombine: self.tempAuditParamC,exType: self.excuteType)}
            
            
            reAddComp()
        }
        
        // 重新添加控件
        func reAddComp() {
            
            let hasTipView = rootTemp.title_item?.count ?? 0 > 0
            var tipView: KSTopTipItem?
            if hasTipView {
                tipView = KSTopTipItem.init(frame: .init(origin: .init(x: 8, y: 0), size: .init(width: KS_SCREEN_WIDTH - 2*6, height: 0)))
                tipView!.title = rootTemp.title_item
                tipView!.text = topTipText
                header.addSubview(tipView!)
            }
            
            for i in 0..<showA.count {
                let oneI = showA[i]
                
                let itemO = oneI.item!
                if itemO.isKind(of: KSImageSelectUtil.self) {
                    itemO.ks_y = bg.tail!.frame.maxY
                    let theone = itemO as! KSImageSelectUtil
                    bg.addv(view: theone)
                }
                if itemO.isKind(of: KSFormBaseItem.self) {
                    let theone = itemO as! KSFormBaseItem
                    if i == 0 {
                        theone.setLineHidden(true)
                    }
                    bg.add(theone)
                }
                if i == 0 {
                    itemO.setRoundType(type: .top)
                }
                
                    
                
                if i == showA.count - 1 {
                    // 有细表, 主表的最后一个控件自动圆角，没细表的时候会用统一的补圆角view
                    if self.detHandler[0].count > 0 {
                        itemO.setRoundType(type: .bottom)
                    }
                }
            }
            
            // 有多细表
            var dmTitle = self.rootTemp.multiDetailsTitles
           
              var segMD = [SegmenttData]()
            if dmTitle.count == 0 {
                dmTitle = ["明细"]
            }
             segMD = dmTitle.compactMap { SegmenttData(id: "",nm: $0) }
             detailZoneV.setCollecDataSource(arr: segMD)
            detailZoneV.setRoundType(type: .top)
             detailZoneV.collecSelected = {indx, sdata in
                 // 避免切换细表 tab 导致需要触发影响等刷新列表发生数组越界崩溃
                 self.tableVw.endEditing(true)
                 
                 DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                     self.cDIndex = indx
                     self.reloadDetData()
                 }
            }
            // 有细表，添加细表头部，一组细表默认添加一个【明细】 头部
            if self.detHandler[0].count > 0 {
                if detailZoneV.superview.isNone {
                    bg.add(detailSeperate)
                    bg.add(detailZoneV)
                }
            }
           
            if hasTipView {
                bg.ks_y = tipView!.ks_height
            } else {
                bg.ks_y = 8
            }
            
            header.ks_height = bg.frame.maxY
            
            KSLog("高度观察----\(header.ks_height)")
            self.tableVw.tableHeaderView = header
            
        }
        
        
        
    }
    
    
    // first 第一次处理显示数据， ，默认为否   刚进来需要触发所有影响但排除  setvalue  setclear setClearDetails
    // 这三个  防止查看进来把数据清空了
    func configTempDataSource(_ first:Bool = false) {
        
        // 先刷细表，因为主表的数据会依赖细表
        self.reloadDetData(first)
        
        
        // 触发一次主表计算
        self.computerAction(first: first)
        // 执行主表的影响
        self.setEffect(first)
        // 再次触发一次主表计算 影响后的值会不一样
        self.computerAction(first: first)
        
        
        
        self.showMainData()
        
        // 再刷一次细表，因为主表又会影响细表
        self.reloadDetData(first)
        
    }
    // 把字典里的数据展示出来 ，仅主表，并同步一次原始ori
    func showMainData() {
        TempLog("执行刷新页面数据")
        // 给控件赋值
        for i in 0..<self.mainHandler.count {
            let tempCurr = self.mainHandler[i].temp!
            if isShowJ(tempCurr,auCombine: self.tempAuditParamC,exType: self.excuteType) {
                let value = any2Str(self.main[tempCurr.field_nm.unwrap])
                
                
                var titleSSS = tempCurr.field_annotation.unwrap
                if tempCurr.is_required == "1" {
                    titleSSS += "*"
                }
                
                if tempCurr.field_type == TemplateType.radio.rawValue {
                    (self.mainHandler[i].item as! KSSwitchItem).setSwitchOn(value == "1")
                } else  if tempCurr.field_type == TemplateType.file.rawValue {
                    
                } else  if tempCurr.field_type == TemplateType.note.rawValue {
                    
                } else  if tempCurr.field_type == TemplateType.map.rawValue {
                    if tempCurr.mapCoordinate.count == 2 {
                        let lon = any2Str(self.main[tempCurr.mapCoordinate[0]])
                        let lat = any2Str(self.main[tempCurr.mapCoordinate[1]])
                        (self.mainHandler[i].item as! KSMapItem).setCoordinate(lon: lon, lat: lat)
                    } else {
                        KSToast("地图参数配置错误")
                    }
                    
                    
                } else if tempCurr.field_type == TemplateType.slidingblock.rawValue {
                    (self.mainHandler[i].item as! KSBlockItem).setBlockValue(nm: value)
                } else {
                    
                    
                    // 计算文本高度
                    let hhh = tempSpCountHeight(value)
                    if hhh > (self.mainHandler[i].item as! KSFormBaseItem).appearance.contentHight {
                        // 计算出来的高度高于配置的高度 使用计算的高度
                        (self.mainHandler[i].item as! KSFormBaseItem).appearance.contentHight(hhh)
                        
                    }
                    
                    (self.mainHandler[i].item as! KSFormBaseItem).setVal(value)
                    (self.mainHandler[i].item as! KSFormBaseItem).setTempTitle(titleSSS)
                }
            }
            
            
        }
        // 根据内容重新调高度
        bg.reFrame(item: bg.head!)
        header.ks_height = bg.frame.maxY
        self.tableVw.tableHeaderView = header
        // 最终给ori赋值,后续观察变化
        oriMain = main
    }
    
    
    func reloadDetData(_ first:Bool = false,indexPath: IndexPath? = nil) {
        
        
        comAndEff(first: first, indexPath: indexPath)
        
        // 从新算高
        
        for i in 0..<self.detHandler[self.cDIndex].count {
            KSLog("-第--\(i)")
            
            self.detHandler[self.cDIndex][i] = countDetailHeight(self.detHandler[self.cDIndex][i],auCombine: self.tempAuditParamC,exType: self.excuteType)
        }
        
        
        self.tableVw.reloadData()
        
    }
    // 先计算  后影响  有影响就再走一遍 直到结束
    func comAndEff(first:Bool,indexPath: IndexPath?) {
        self.computerAction(first:first,indexPath:indexPath)
        let effected = self.setDetEffect(first)
        self.oriDetArr[self.cDIndex] = self.detHandler[self.cDIndex].compactMap{$0.dic}
        if effected {
            comAndEff(first: first, indexPath: indexPath)
        }
    }
    
    
}


// MARK: 细表
extension ConfigMenuForm {
    func numberOfSections(in tableView: UITableView) -> Int {
        
        var countX = self.detHandler[self.cDIndex].count
        var opflag = ""
        if self.rootTemp.multiDetailsOperates.count > 0 {
            opflag = self.rootTemp.multiDetailsOperates[self.cDIndex]
        } else {
            opflag = self.rootTemp.is_operation_detail.unwrap
        }
        if isOpeDetail(isOpFlag: opflag) {
            countX += 1
        }
        return countX
        
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == self.detHandler[self.cDIndex].count {
            // ‘添加明细’按钮
            return 1
        } else {
            if  any2Str(self.detHandler[self.cDIndex][section].dic[TKey.openx]) == TRUE {
                return 1
            } else {
                return 0
            }
        }
        
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section != self.detHandler[self.cDIndex].count {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: ConfigMenuFormCell.identifier, for: indexPath) as? ConfigMenuFormCell else {
                fatalError()
            }
            
            let  currentDTemp = self.detHandler[self.cDIndex][indexPath.section].temp.filter { isShowJ($0,auCombine: self.tempAuditParamC,exType: self.excuteType) }
            cell.excuteType = self.excuteType
            cell.u_superVC = self
            cell.auditParamCombine = self.tempAuditParamC
            
            let oneCombine = self.detHandler[self.cDIndex][indexPath.section]
            
            cell.configView(detO: oneCombine)
            cell.one = oneCombine.dic
            
            
            
            for y in 0..<currentDTemp.count {
                let oneD = currentDTemp[y]
                var theitem:KSFormBaseItem?
                theitem = (cell.itemArr[y] as? KSFormHItem).isSome ? (cell.itemArr[y] as? KSFormHItem) : (cell.itemArr[y] as? KSFormVItem)
                switch oneD.field_type {
                case TemplateType.input.rawValue,
                    TemplateType.number.rawValue,
                    TemplateType.integer.rawValue,
                    TemplateType.number2.rawValue:
                   
                    theitem?.textEndEditClo = { [indexPath] str in
                        self.detHandler[self.cDIndex][indexPath.section].dic[oneD.field_nm.unwrap] = str
                        
                        self.reloadDetData(indexPath:indexPath)
                    }
                    
                case  TemplateType.date.rawValue:
                    theitem?.actionClosure = {
                        
                        
                        TempHelper.shared.showTempDate(vc:self,onexx: oneD) { [indexPath] str in
                            
                            self.detHandler[self.cDIndex][indexPath.section].dic[oneD.field_nm.unwrap] = str
                            self.reloadDetData(indexPath:indexPath)
                            
                            
                        }
                        
                        
                    }
                    
                case  TemplateType.datetime.rawValue :
                    theitem?.actionClosure = {
                        self.dateTimePick.resultClosure = { str in
                            self.detHandler[self.cDIndex][indexPath.section].dic[oneD.field_nm.unwrap] = str
                            self.reloadDetData(indexPath:indexPath)
                            
                        }
                        self.dateTimePick.present()
                        
                    }
                    
                case  TemplateType.lov.rawValue ,
                    TemplateType.btnevent_lov.rawValue:
                    theitem?.actionClosure = {
                        
                        if self.dependenceVali(onexx: oneD, indexPath: indexPath) {
                            self.showLov(onexx: oneD, indexPath: indexPath)
                        }
                    }
                    
                    
                case TemplateType.tree.rawValue:
                    theitem?.actionClosure = {
                        
                        if self.dependenceVali(onexx: oneD, indexPath: indexPath) {
                            self.showTree(onexx: oneD, indexPath: indexPath)
                        }
                        
                    }
                    
                case  TemplateType.btnevent.rawValue ,
                    TemplateType.btnevent_exec.rawValue :
                    theitem?.actionClosure = {
                        if self.dependenceVali(onexx: oneD, indexPath: indexPath) {
                            self.continueUrl(onexx: oneD, indexPath: indexPath)
                        }
                     }
 
                case  TemplateType.localSelect.rawValue :
                    theitem?.actionClosure = {
                        
                        self.showXLSelect(onexx: oneD, indexPath: indexPath)
                        
                    }
                    
           
                    
                    
                case  TemplateType.coordinate.rawValue :
                    theitem?.actionClosure = {
                        if self.dependenceVali(onexx: oneD, indexPath: indexPath) {
                            self.go2MapVC(onexx: oneD, indexPath: indexPath)
                        }
                        
                    }
                    
                case  TemplateType.gangedlov.rawValue :
                    theitem?.actionClosure = {
                        
                        
                        self.showLiandong(oneD: oneD, indexPath: indexPath)
                        
                        
                    }
                case  TemplateType.slidingblock.rawValue :
                    (cell.itemArr[y] as! KSBlockItem).blockValueChangeClo = { segData in
                        let sBack = oneD.selectDataBack!
                        self.detHandler[self.cDIndex][indexPath.section].dic[sBack.idBack.unwrap] = segData.id
                        self.detHandler[self.cDIndex][indexPath.section].dic[sBack.nmBack.unwrap] = segData.nm
                        self.reloadDetData(indexPath:indexPath)
                    }
                    
                case  TemplateType.radio.rawValue :
                    (cell.itemArr[y] as! KSSwitchItem).switchValueChangeClo = { flag in
                        self.detHandler[self.cDIndex][indexPath.section].dic[oneD.field_nm.unwrap] = flag ? "1" : "0"
                        self.reloadDetData(indexPath:indexPath)
                        
                    }
                default:
                    
                    break
                }
                
                
                
            }
            cell.detAddImages = {[indexPath] util,imgvideos in
                self.detHandler[self.cDIndex][indexPath.section].imgArray += imgvideos
                
            }
            cell.detAddFiles = {[indexPath] util,files in
                self.detHandler[self.cDIndex][indexPath.section].imgArray += files
                
            }
            cell.detDeleteImage = {[indexPath] util,indexx in
                alertUtil(self, title: "确认删除", operateS: [nameAction(name: "确定", action: { _ in
                    let one = self.detHandler[self.cDIndex][indexPath.section].imgArray[indexx]
                    let dicOne = self.detHandler[self.cDIndex][indexPath.section].dic
                    let fArr = self.detHandler[self.cDIndex][indexPath.section].temp.filter { $0.field_type == TemplateType.file.rawValue }
                    let temp = fArr.first!
                    if one.idkey.unwrap.isEmpty {
                        self.detHandler[self.cDIndex][indexPath.section].imgArray.remove(at: indexx)
                        util.deleteLocalImg(tag: indexx)
                        
                    } else {
                        deleImage_temp(templateDic:self.templateDic,idkey:one.idkey.unwrap,vou_id: any2Str(dicOne[TKey.id_key]),module_id: self.rootTemp.module_id.unwrap,temp: temp) {
                            self.detHandler[self.cDIndex][indexPath.section].imgArray.remove(at: indexx)
                            util.deleteLocalImg(tag: indexx)
                            
                        }
                    }
                })])
            }
            
            
            return cell
        }  else  {  // +
            let cell = tableView.dequeueReusableCell(withIdentifier: GlobalAddTableCell.identifier, for: indexPath) as! GlobalAddTableCell
            cell.titleLab.text = "+  添加明细"
            return cell
        }
        
    }
    
    
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == self.detHandler[self.cDIndex].count {// 添加细表事件
            if  intTran(rootTemp.detail_num_max) > 0 {
                guard self.detHandler[self.cDIndex].count < intTran(rootTemp.detail_num_max) else {
                    KSToast("细表只能\(intTran(rootTemp.detail_num_max))条")
                    return
                }
            }
            let mDet  = temp2Dic(self.tempDet[self.cDIndex],rootTemp: rootTemp)
            let final = deepMerge(self.defaultOneDetail[self.cDIndex], mDet)
            
            
            self.detHandler[self.cDIndex].appendAndCountH(DetailsTempCom(temp: self.tempDet[self.cDIndex], dic: final),auCombine: self.tempAuditParamC,exType: self.excuteType)
            self.oriDetArr[self.cDIndex] = self.detHandler[self.cDIndex].compactMap{$0.dic}
            self.configTempDataSource()
            self.activeDetailRow(indexx: self.detHandler[self.cDIndex].count - 1,status: "true")
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == self.detHandler[self.cDIndex].count  {
            return sectionHeaderHeight
        }   else {
            return self.detHandler[self.cDIndex][indexPath.section].detailHeight
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == self.detHandler[self.cDIndex].count {
            return 0
        } else {
            return sectionHeaderHeight
        }
        
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        
        
        guard let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: GlobalSectionHeader.identifier) as? GlobalSectionHeader else {
            fatalError()
        }
        let tap = UITapGestureRecognizer()
        tap.numberOfTapsRequired = 1
        tap.addTap { [unowned self] _ in
            if any2Str(self.detHandler[self.cDIndex][section].dic[TKey.openx]) == TRUE {
                self.activeDetailRow(indexx: section,status:"false")
            } else {
                self.activeDetailRow(indexx: section,status:"true")
            }
            
        }
        
        headerView.addGestureRecognizer(tap)
        
        var opflag = ""
        if self.rootTemp.multiDetailsOperates.count > 0 {
            opflag = self.rootTemp.multiDetailsOperates[self.cDIndex]
        } else {
            opflag = self.rootTemp.is_operation_detail.unwrap
        }
        if isOpeDetail(isOpFlag: opflag) {
            
            
            headerView.deleteClo = {
                
                self.view.endEditing(true)
                
                alertUtil(self, title: "确认删除？", operateS: [nameAction(name: "确定", action: { (_) in
                    self.detHandler[self.cDIndex].remove(at: section)
                    self.oriDetArr[self.cDIndex] = self.detHandler[self.cDIndex].compactMap{$0.dic}
                    
                    DispatchQueue.main.async {
                        self.configTempDataSource()
                        
                        if section == 0 && self.detHandler[self.cDIndex].count == 0 {
                            // 保持至少有一条
                            let mDet  = temp2Dic(self.tempDet[self.cDIndex], rootTemp: self.rootTemp)
                            let final = deepMerge(self.defaultOneDetail[self.cDIndex], mDet)
                            
                            
                            self.detHandler[self.cDIndex].appendAndCountH(DetailsTempCom(temp: self.tempDet[self.cDIndex], dic: final),auCombine: self.tempAuditParamC,exType: self.excuteType)
                            self.oriDetArr[self.cDIndex] = self.detHandler[self.cDIndex].compactMap{$0.dic}
                            self.configTempDataSource()
                            self.activeDetailRow(indexx: self.detHandler[self.cDIndex].count - 1,status: "true")
                        }
                    }
                    
 
                })])
                
            }
            headerView.delBtn.isHidden = false
        } else {
            headerView.delBtn.isHidden = true
        }
        
        
        
        if  self.detHandler[self.cDIndex].count > section ,
            any2Str(self.detHandler[self.cDIndex][section].dic[TKey.openx]) == TRUE {
            headerView.setOpenx(flag: true)
            
        } else {
            headerView.setOpenx(flag: false)
        }
        if section < self.detHandler[self.cDIndex].count {
            let subH = self.detHandler[self.cDIndex][section].temp.filter{$0.detailTitleGramar != ""}
            if subH.count > 0  {
                KSLog("刷新细表头部")
                let vvv = getDolVal(subH.first!.detailTitleGramar,currDet: self.detHandler[self.cDIndex][section].dic,rootTemp: rootTemp).0.replacingOccurrences(of: "\\n", with: "\n")
                headerView.setTitle(vvv)
            } else {
                headerView.setTitle("明细(\(section + 1))")
             }
        }
        
        
        
        
        
        return headerView
        
        
    }
    
    
}



